<template>
  <CustomScrollbar class="home-scroll">
    <div class="home">
    <!-- 欢迎区域 -->
    <section class="hero-section">
      <div class="hero-content">
        <h1 class="hero-title">欢迎来到乐享作坊</h1>
        <p class="hero-subtitle">发现你喜欢的音乐，享受音乐带来的美好时光</p>
      </div>
    </section>

    <!-- 推荐音乐 -->
    <section class="section">
      <div class="section-header">
        <h2 class="section-title">为你推荐</h2>
        <router-link to="/recommended" class="view-all-btn">查看全部</router-link>
      </div>
      <div class="carousel-container" @mouseenter="showButtons('recommended')" @mouseleave="hideButtons('recommended')">
        <button 
          class="carousel-btn carousel-btn-left" 
          @click="scrollLeft('recommended')" 
          :disabled="!canScrollLeft.recommended"
          v-show="showArrows.recommended && canScrollLeft.recommended"
        >
          <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
            <path d="M11.354 1.646a.5.5 0 0 1 0 .708L5.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0z"/>
          </svg>
        </button>
        <div class="music-carousel" ref="recommendedCarousel" @wheel="handleWheel($event, 'recommended')">
          <div class="music-card" v-for="music in recommendedMusic.slice(0, 10)" :key="music.musicId">
            <div class="card-cover-container">
              <img v-if="music.coverPath" :src="music.coverPath" :alt="music.title" class="card-cover">
              <MusicIcon v-else :size="160" class="card-cover" />
              <button class="play-overlay" @click="playMusic(music)">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M8 5v14l11-7z"/>
                </svg>
              </button>

            </div>
            <div class="card-info">
              <h3 class="card-title">{{ music.title }}</h3>
              <p class="card-subtitle">{{ music.artist }}</p>
            </div>
          </div>
        </div>
        <button 
          class="carousel-btn carousel-btn-right" 
          @click="scrollRight('recommended')" 
          :disabled="!canScrollRight.recommended"
          v-show="showArrows.recommended && canScrollRight.recommended"
        >
          <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
            <path d="M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z"/>
          </svg>
        </button>
      </div>
    </section>

    <!-- 最近播放 -->
    <section class="section">
      <div class="section-header">
        <h2 class="section-title">最近播放</h2>
        <router-link to="/recent" class="view-all-btn">查看全部</router-link>
      </div>
      
      <div v-if="recentMusic.length === 0" class="empty-recent">
        <div class="empty-icon">🕒</div>
        <h3>还没有播放记录</h3>
        <p>开始播放一些音乐，它们会显示在这里</p>
      </div>
      
      <div v-else class="carousel-container" @mouseenter="showButtons('recent')" @mouseleave="hideButtons('recent')">
        <button 
          class="carousel-btn carousel-btn-left" 
          @click="scrollLeft('recent')" 
          :disabled="!canScrollLeft.recent"
          v-show="showArrows.recent && canScrollLeft.recent"
        >
          <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
            <path d="M11.354 1.646a.5.5 0 0 1 0 .708L5.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0z"/>
          </svg>
        </button>
        <div class="recent-carousel" ref="recentCarousel" @wheel="handleWheel($event, 'recent')">
          <div class="music-card" v-for="(music, index) in recentMusic.slice(0, 10)" :key="music.musicId">
            <div class="card-cover-container">
              <img v-if="music.coverPath" :src="music.coverPath" :alt="music.title" class="card-cover">
              <MusicIcon v-else :size="160" class="card-cover" />
              <button class="play-overlay" @click="playMusic(music)">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M8 5v14l11-7z"/>
                </svg>
              </button>
              
            </div>
            <div class="card-info">
              <h3 class="card-title">{{ music.title }}</h3>
              <p class="card-subtitle">{{ music.artist }}</p>
              <p class="card-time">{{ formatPlayTime(music.lastPlayTime) }}</p>
            </div>
          </div>
        </div>
        <button 
          class="carousel-btn carousel-btn-right" 
          @click="scrollRight('recent')" 
          :disabled="!canScrollRight.recent"
          v-show="showArrows.recent && canScrollRight.recent"
        >
          <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
            <path d="M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z"/>
          </svg>
        </button>
      </div>
    </section>
    </div>
  </CustomScrollbar>
</template>

<script>
import MusicIcon from '@/components/MusicIcon.vue'
import CustomScrollbar from '@/components/CustomScrollbar.vue'
import { musicAPI, playlistAPI } from '@/utils/api'

export default {
  components: {
    MusicIcon,
    CustomScrollbar
  },
  name: 'HomeView',
  data() {
    return {
      recommendedMusic: [],
      recentMusic: [],
      loading: false,
      canScrollLeft: {
        recommended: false,
        recent: false
      },
      canScrollRight: {
        recommended: true,
        recent: true
      },
      showArrows: {
        recommended: false,
        recent: false
      }
    }
  },
  async mounted() {
    await this.loadData()
    // 加载收藏列表
    await this.$store.dispatch('player/loadFavorites')
  },
  computed: {
    favorites() {
      return this.$store.state.player.favorites || []
    }
  },
  methods: {
    async loadData() {
      this.loading = true
      try {
        // 并行加载推荐音乐和最近播放
        await Promise.all([
          this.loadRecommendedMusic(),
          this.loadRecentMusic()
        ])
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$toast?.error('加载数据失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    
    async loadRecommendedMusic() {
      try {
        // 使用推荐音乐API获取智能推荐的音乐
        const response = await musicAPI.getRecommendedMusic(20)
        if (response.music && response.music.length > 0) {
          this.recommendedMusic = response.music.map(music => ({
            musicId: music.musicId,
            title: music.name,
            artist: music.singer,
            coverPath: this.buildCoverUrl(music.coverPath),
            duration: music.duration,
            filePath: this.buildAudioUrl(music.filePath)
          }))
          console.log('成功加载推荐音乐:', this.recommendedMusic.length, '首')
        } else {
          console.warn('API返回空数据，recommendedMusic保持为空')
          this.recommendedMusic = []
        }
      } catch (error) {
        console.error('加载推荐音乐失败:', error)
        this.recommendedMusic = []
      }
    },
    
    async loadRecentMusic() {
      try {
        // 如果前台用户已登录，获取真实的播放历史
        const userToken = localStorage.getItem('userToken')
        const userExpiry = localStorage.getItem('userTokenExpiry')
        
        if (userToken && userToken !== 'null' && userToken !== '' && userExpiry && Date.now() < parseInt(userExpiry)) {
          try {
            const response = await playlistAPI.getPlayHistory(0, 10)
            if (response.success && response.playHistory) {
              this.recentMusic = response.playHistory.map(item => ({
                musicId: item.music.musicId,
                title: item.music.name,
                artist: item.music.singer,
                coverPath: this.buildCoverUrl(item.music.coverPath),
                duration: item.music.duration,
                filePath: this.buildAudioUrl(item.music.filePath),
                lastPlayTime: new Date(item.playTime)
              }))
              console.log('成功加载播放历史:', this.recentMusic.length, '首')
            } else {
              console.warn('用户已登录但没有播放历史')
              this.recentMusic = []
            }
          } catch (historyError) {
            console.warn('获取播放历史失败，可能token无效:', historyError.message)
            // 如果token无效，清除它
            if (historyError.response?.status === 401 || historyError.response?.status === 403) {
              localStorage.removeItem('userToken')
              localStorage.removeItem('userInfo')
              localStorage.removeItem('userTokenExpiry')
            }
            this.recentMusic = []
          }
        } else {
          console.log('前台用户未登录或token过期，不显示播放历史')
          this.recentMusic = []
        }

        // 初始化滚动按钮状态
        this.$nextTick(() => {
          this.updateScrollButtons('recommended');
          this.updateScrollButtons('recent');
        });
      } catch (error) {
        console.error('加载最近播放失败:', error)
        this.recentMusic = []
      }
    },
    async playMusic(music) {
      try {
        console.log('播放音乐:', music.title)
        
        // 构建当前页面的播放列表（推荐音乐 + 最近播放）
        const allMusic = [...this.recommendedMusic, ...this.recentMusic]
        const playlist = allMusic.map(m => ({
          musicId: m.musicId,
          id: m.musicId,
          title: m.title,
          name: m.title,
          artist: m.artist,
          singer: m.artist,
          coverPath: m.coverPath,
          cover: m.coverPath,
          duration: m.duration,
          filePath: m.filePath,
          src: m.filePath
        }))
        
        // 设置播放列表
        this.$store.commit('player/SET_PLAYLIST', playlist)
        
        // 找到当前音乐在播放列表中的索引
        const currentIndex = playlist.findIndex(item => item.musicId === music.musicId)
        if (currentIndex !== -1) {
          this.$store.commit('player/SET_CURRENT_INDEX', currentIndex)
        }
        
        // 播放当前音乐
        this.$store?.dispatch('player/playMusic', {
          musicId: music.musicId,
          id: music.musicId,
          title: music.title,
          name: music.title,
          artist: music.artist,
          singer: music.artist,
          coverPath: music.coverPath,
          cover: music.coverPath,
          duration: music.duration,
          filePath: music.filePath,
          src: music.filePath
        })
        
      } catch (error) {
        console.error('播放音乐失败:', error)
      }
    },
    async toggleFavorite(music) {
      try {
        const userToken = localStorage.getItem('userToken')
        const userExpiry = localStorage.getItem('userTokenExpiry')
        
        // 检查前台用户登录状态
        if (!userToken || userToken === 'null' || userToken === '' || !userExpiry || Date.now() > parseInt(userExpiry)) {
          if (window.app && window.app.showToast) {
            window.app.showToast('请先登录才能收藏音乐', 'warning')
          } else {
            alert('请先登录才能收藏音乐')
          }
          return
        }
        
        const musicId = music.musicId
        const isFavorited = this.favorites.includes(musicId)
        
        if (isFavorited) {
          // 取消收藏
          await playlistAPI.removeFavorite(musicId)
          this.$store.commit('player/REMOVE_FAVORITE', musicId)
          if (window.app && window.app.showToast) {
            window.app.showToast('已取消收藏', 'info')
          }
        } else {
          // 添加收藏
          await playlistAPI.addFavorite(musicId)
          this.$store.commit('player/ADD_FAVORITE', musicId)
          if (window.app && window.app.showToast) {
            window.app.showToast('已添加到我的喜欢', 'success')
          }
        }
        
        console.log('收藏操作成功:', music.title)
      } catch (error) {
        console.error('收藏操作失败:', error)
        if (window.app && window.app.showToast) {
          window.app.showToast('收藏操作失败，请重试', 'error')
        }
        if (error.response?.status === 401 || error.response?.status === 403) {
          localStorage.removeItem('userToken')
          localStorage.removeItem('userInfo')
          localStorage.removeItem('userTokenExpiry')
          this.$store.commit('player/SET_FAVORITES', [])
        }
      }
    },
    isFavorite(musicId) {
      return this.$store.getters['player/favorites'].includes(musicId)
    },
    formatDuration(seconds) {
      // 处理各种输入情况
      if (seconds === null || seconds === undefined || seconds === 0) return '-'
      
      // 确保是数字类型
      const numSeconds = Number(seconds)
      if (isNaN(numSeconds) || numSeconds < 0) return '-'
      
      // 计算分钟和秒
      const minutes = Math.floor(numSeconds / 60)
      const remainingSeconds = Math.floor(numSeconds % 60)
      
      // 格式化输出
      if (minutes >= 60) {
        // 超过1小时的情况
        const hours = Math.floor(minutes / 60)
        const remainingMinutes = minutes % 60
        return `${hours}:${remainingMinutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
      } else {
        // 普通情况：分:秒
        return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
      }
    },
    formatPlayTime(date) {
      const now = new Date()
      const diff = now - date
      const hours = Math.floor(diff / (1000 * 60 * 60))
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      
      if (hours < 1) return '刚刚'
      if (hours < 24) return `${hours}小时前`
      if (days === 1) return '昨天'
      if (days < 7) return `${days}天前`
      
      return date.toLocaleDateString('zh-CN')
    },
    showButtons(carousel) {
      this.showArrows[carousel] = true;
    },
    hideButtons(carousel) {
      this.showArrows[carousel] = false;
    },
    handleWheel(event, carousel) {
      // 只有当按住 Shift 键时才处理滚轮事件
      if (!event.shiftKey) {
        return;
      }
      
      event.preventDefault();
      const container = this.$refs[carousel + 'Carousel'];
      
      if (event.deltaY > 0) {
        // 向下滚动 - 向右滚动容器
        container.scrollLeft += 200;
      } else {
        // 向上滚动 - 向左滚动容器
        container.scrollLeft -= 200;
      }
      
      this.updateScrollButtons(carousel);
    },
    scrollLeft(carousel) {
      const container = this.$refs[carousel + 'Carousel'];
      container.scrollLeft -= 200;
      this.updateScrollButtons(carousel);
    },
    scrollRight(carousel) {
      const container = this.$refs[carousel + 'Carousel'];
      container.scrollLeft += 200;
      this.updateScrollButtons(carousel);
    },
    updateScrollButtons(carousel) {
      this.$nextTick(() => {
        const container = this.$refs[carousel + 'Carousel'];
        if (container) {
          this.canScrollLeft[carousel] = container.scrollLeft > 0;
          this.canScrollRight[carousel] = container.scrollLeft < container.scrollWidth - container.clientWidth;
        }
      });
    },
    // 构建封面图片URL
    buildCoverUrl(coverPath) {
      if (!coverPath) return null
      
      // 如果已经是完整URL，直接使用
      if (coverPath.startsWith('http://') || coverPath.startsWith('https://')) {
        return coverPath
      }
      
      // 从路径中提取文件名
      let fileName = coverPath
      if (coverPath.includes('/uploads/covers/')) {
        fileName = coverPath.split('/').pop()
      } else if (coverPath.includes('/')) {
        fileName = coverPath.split('/').pop()
      }
      
      return `http://localhost:2025/api/files/covers/${fileName}`
    },
    
    // 构建音频文件URL
    buildAudioUrl(filePath) {
      if (!filePath) return null
      
      // 如果已经是完整URL，直接使用
      if (filePath.startsWith('http://') || filePath.startsWith('https://')) {
        return filePath
      }
      
      // 从路径中提取文件名
      let fileName = filePath
      if (filePath.includes('/uploads/songs/')) {
        fileName = filePath.split('/').pop()
      } else if (filePath.includes('/')) {
        fileName = filePath.split('/').pop()
      }
      
      return `http://localhost:2025/api/files/songs/${fileName}`
    },
  }
}
</script>

<style scoped>
.home-scroll {
  height: 100%;
}

.home {
  padding-bottom: 24px; /* 确保底部有适当的间距 */
}

/* 欢迎区域 */
.hero-section {
  background: linear-gradient(135deg, #1DB954 0%, #191414 100%);
  padding: 80px 0;
  text-align: center;
  border-radius: 8px;
  margin-bottom: 48px;
}

.hero-content {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 24px;
}

.hero-title {
  font-size: 3.5rem;
  font-weight: bold;
  margin-bottom: 16px;
  color: white;
}

.hero-subtitle {
  font-size: 1.2rem;
  color: #b3b3b3;
  margin: 0;
}

/* 通用区块样式 */
.section {
  margin-bottom: 48px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-title {
  font-size: 2rem;
  font-weight: bold;
  margin: 0;
  color: white;
}

.view-all-btn {
  color: #b3b3b3;
  text-decoration: none;
  font-size: 14px;
  font-weight: bold;
  background: none;
  border: none;
  cursor: pointer;
  transition: color 0.2s;
}

.view-all-btn:hover {
  color: white;
}

/* 轮播样式 */
.carousel-container {
  position: relative;
  margin-bottom: 32px;
}

.carousel-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.7);
  border: none;
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  opacity: 0;
  visibility: hidden;
}

.carousel-container:hover .carousel-btn {
  opacity: 1;
  visibility: visible;
}

.carousel-btn:hover:not(:disabled) {
  background: rgba(0, 0, 0, 0.9);
  transform: translateY(-50%) scale(1.1);
}

.carousel-btn:disabled {
  opacity: 0;
  visibility: hidden;
  cursor: not-allowed;
}

.carousel-btn-left {
  left: -16px;
}

.carousel-btn-right {
  right: -16px;
}

.music-carousel,
.recent-carousel {
  display: flex;
  gap: 24px;
  overflow-x: auto;
  scroll-behavior: smooth;
  scrollbar-width: none;
  -ms-overflow-style: none;
  padding: 8px 0;
}

.music-carousel::-webkit-scrollbar,
.recent-carousel::-webkit-scrollbar {
  display: none;
}

/* 统一卡片样式 */
.music-card {
  background: #181818;
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  min-width: 180px;
  max-width: 180px;
  flex-shrink: 0;
}

.music-card:hover {
  background: #282828;
  transform: translateY(-2px);
}

.card-cover-container {
  position: relative;
  margin-bottom: 16px;
  width: 148px;
  height: 148px;
  border-radius: 8px;
  overflow: hidden;
  background: #333;
}

.card-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.play-overlay {
  position: absolute;
  bottom: 8px;
  right: 8px;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: #1db954;
  border: none;
  color: black;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  opacity: 0;
  transform: translateY(8px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
}

.music-card:hover .play-overlay {
  opacity: 1;
  transform: translateY(0);
}

.play-overlay:hover {
  transform: scale(1.05);
  background: #1ed760;
}





.card-info {
  text-align: left;
}

.card-title {
  font-size: 16px;
  font-weight: 700;
  color: white;
  margin: 0 0 4px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.5;
}

.card-subtitle {
  font-size: 14px;
  color: #b3b3b3;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.5;
}

.card-time {
  font-size: 12px;
  color: #888;
  margin: 4px 0 0 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.3;
}

/* 音乐列表布局 */
.music-list {
  background: #181818;
  border-radius: 8px;
  overflow: hidden;
}

.music-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #282828;
  transition: background 0.2s;
}

.music-item:hover {
  background: #282828;
}

.music-item:last-child {
  border-bottom: none;
}

.music-rank {
  width: 32px;
  text-align: center;
  color: #b3b3b3;
  font-weight: bold;
  margin-right: 16px;
}

.music-thumbnail {
  width: 48px;
  height: 48px;
  border-radius: 4px;
  margin-right: 16px;
}

.music-details {
  flex: 1;
  min-width: 0;
}

.music-name {
  font-size: 16px;
  font-weight: 500;
  color: white;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 4px;
}

.play-time {
  color: #b3b3b3;
  margin-right: 16px;
  min-width: 80px;
  text-align: right;
  font-size: 14px;
}

.music-duration {
  color: #b3b3b3;
  margin-right: 16px;
  min-width: 50px;
  text-align: right;
}

.music-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  background: none;
  border: none;
  color: #b3b3b3;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.2s;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn:hover {
  color: white;
  background: rgba(255, 255, 255, 0.1);
}

.favorited {
  color: #1DB954 !important;
}

/* 最近播放空状态 */
.empty-recent {
  text-align: center;
  padding: 48px 24px;
  color: #b3b3b3;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-recent h3 {
  color: white;
  font-size: 1.5rem;
  margin-bottom: 8px;
}

.empty-recent p {
  margin: 0;
  font-size: 14px;
}

/* 分类网格 */
.category-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.category-card {
  aspect-ratio: 2/1;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  align-items: flex-end;
  text-decoration: none;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: transform 0.2s;
  overflow: hidden;
  position: relative;
}

.category-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0.3) 100%);
}

.category-card h3 {
  position: relative;
  z-index: 1;
  margin: 0;
}

.category-card:hover {
  transform: scale(1.02);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .music-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .hero-title {
    font-size: 2.5rem;
  }
  
  .music-grid {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    gap: 12px;
  }
  
  .music-card {
    padding: 12px;
  }
  
  .music-item {
    padding: 8px 12px;
  }
  
  .play-time {
    display: none;
  }
}

@media (max-width: 480px) {
  .hero-title {
    font-size: 2rem;
  }
  
  .music-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }
}
</style>

